package com.zsd.android.opengldemo.filter;

import android.content.Context;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;

import com.zsd.android.opengldemo.R;
import com.zsd.android.opengldemo.utils.OpenGLUtils;

/**
 * 主要是获取摄像头数据并且创建FBO
 */
public class CameraFilter extends AbstractFilter {

    //FBO
    private int[] mFrameBuffer;
    private int[] mFrameBufferTextures;

    public CameraFilter(Context mContext) {
        super(mContext, R.raw.camera_vertex, R.raw.camera_frag);
    }

    @Override
    protected void initCoordinate() {
        mTextureBuffer.clear();
        //原始坐标，摄像头是颠倒的90度，镜像
        float[] TEXTURE = {
                0.0f, 0.0f,
                1.0f, 1.0f,
                0.0f, 1.0f,
                1.0f, 1.0f
        };
        //修复
        mTextureBuffer.put(TEXTURE);
    }

    public void onReady(int width, int height) {
        super.onReady(width, height);
        mFrameBuffer = new int[1];
        //生成FBO
        GLES20.glGenFramebuffers(1, mFrameBuffer, 0);
        //实例化一个纹理，目的是让纹理和FBO进行绑定，之后只用对纹理进行操作
        mFrameBufferTextures = new int[1];
        OpenGLUtils.glGenTextures(mFrameBufferTextures);
        //将纹理与FBO绑定
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mFrameBufferTextures[0]);
        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBuffer[0]);
        //设置纹理显示信息 高度宽度
        GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, mWidth, mHeight, 0,
                GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
        //将纹理和FBO联系
        GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
                GLES20.GL_TEXTURE_2D, mFrameBufferTextures[0], 0);
        //解绑
        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
    }

    @Override
    public int onDrawFrame(int textureId) {
        //设置显示窗口
        GLES20.glViewport(0, 0, mWidth, mHeight);
        //使用着色器
        GLES20.glUseProgram(mProgram);

        GLES20.glVertexAttribPointer(vPosition, 2, GLES20.GL_FLOAT, false, 0, mVertexBuffer);
        GLES20.glEnableVertexAttribArray(vPosition);

        mTextureBuffer.position(0);
        GLES20.glVertexAttribPointer(vCoord, 2, GLES20.GL_FLOAT, false, 0, mTextureBuffer);
        GLES20.glEnableVertexAttribArray(vCoord);

        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId);

        GLES20.glUniform1i(vTexture, 0);
        //绘制
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
        return mFrameBufferTextures[0];
    }
}
